/**
 * 
 */
package dt.inlee.system.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.VisitorFieldValidator;
import com.sjb.common.util.MD5;

import dt.inlee.common.constant.CommonConstant;
import dt.inlee.common.exception.FrameworkException;
import dt.inlee.common.util.BaseUtil;
import dt.inlee.common.util.HqlUtil;
import dt.inlee.common.util.SystemResourceUtil;
import dt.inlee.common.vo.PageBean;
import dt.inlee.domain.SysOrganization;
import dt.inlee.domain.SysRole;
import dt.inlee.domain.SysUser;
import dt.inlee.system.service.SysOrganizationService;
import dt.inlee.system.service.SysRoleService;
import dt.inlee.system.service.SysUserService;
import dt.inlee.system.vo.DictionaryBean;
import dt.inlee.system.vo.SysRoleBean;
import dt.inlee.system.vo.SysUserBean;
import dt.inlee.system.vo.SysUserLoginBean;

/**
 * @功能说明：系统用户控制层
 * @作者： 印鲜刚
 * @创建日期： 2010-5-7 @
 */
@SuppressWarnings("serial")
@Scope("prototype")
@Controller("sysUserAction")
public class SysUserAction extends ActionSupport {
    private static Logger logger = Logger.getLogger(SysUserAction.class);

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOrganizationService sysOrganizationService;
    @Autowired
    private SysRoleService sysRoleService;

    private SysUserBean sysUserBean = new SysUserBean();
    private PageBean pageBean = new PageBean();
    private SysUserLoginBean sysUserLoginBean = new SysUserLoginBean();
    private String newpassword;
    private List<SysRoleBean> sysRoleBeans = new ArrayList<SysRoleBean>();
    private List<SysUserBean> sysUserBeans = new ArrayList<SysUserBean>();
    private List<DictionaryBean> genderTag = new ArrayList<DictionaryBean>();
    private List<DictionaryBean> staffKindTag = new ArrayList<DictionaryBean>();
    // 处理结果
    private boolean result = false;
    // 登录用户密码
    private String oldPassword;
    private JSONObject jsonObject;

    public JSONObject getJsonObject() {
        return jsonObject;
    }

    public void setJsonObject(JSONObject jsonObject) {
        this.jsonObject = jsonObject;
    }

    public SysUserAction() throws FrameworkException {
        this.genderTag = SystemResourceUtil.getInstance().getResourceAsList("gender");
        this.staffKindTag = SystemResourceUtil.getInstance().getResourceAsList("staffKind");
    }

    public String getNewpassword() {
        return newpassword;
    }

    public void setNewpassword(String newpassword) {
        this.newpassword = newpassword;
    }

    public SysUserLoginBean getSysUserLoginBean() {
        return sysUserLoginBean;
    }

    public void setSysUserLoginBean(SysUserLoginBean sysUserLoginBean) {
        this.sysUserLoginBean = sysUserLoginBean;
    }

    public PageBean getPageBean() {
        return pageBean;
    }

    public void setPageBean(PageBean pageBean) {
        this.pageBean = pageBean;
    }

    public List<SysRoleBean> getSysRoleBeans() {
        return sysRoleBeans;
    }

    public void setSysRoleBeans(List<SysRoleBean> sysRoleBeans) {
        this.sysRoleBeans = sysRoleBeans;
    }

    public SysUserBean getSysUserBean() {
        return sysUserBean;
    }

    @Validations(visitorFields = {@VisitorFieldValidator(message = "test", fieldName = "model", appendPrefix = false)})
    public void setSysUserBean(SysUserBean sysUserBean) {
        this.sysUserBean = sysUserBean;
    }

    public List<SysUserBean> getSysUserBeans() {
        return sysUserBeans;
    }

    public void setSysUserBeans(List<SysUserBean> sysUserBeans) {
        this.sysUserBeans = sysUserBeans;
    }

    public List<DictionaryBean> getGenderTag() {
        return genderTag;
    }

    public void setGenderTag(List<DictionaryBean> genderTag) {
        this.genderTag = genderTag;
    }

    public List<DictionaryBean> getStaffKindTag() {
        return staffKindTag;
    }

    public void setStaffKindTag(List<DictionaryBean> staffKindTag) {
        this.staffKindTag = staffKindTag;
    }

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

    public String getOldPassword() {
        return oldPassword;
    }

    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }

    /**
     * 进入用户添加页面
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "createSysUser", results = @Result(name = "success", location = "/page/system/sys_user_detail.jsp"))
    @SkipValidation()
    public String createSysUser() throws FrameworkException {
        SysUserLoginBean sysUserLoginBean =
                (SysUserLoginBean) ActionContext.getContext().getSession().get(CommonConstant.SESSION_USER);
        SysUser sysUser = this.sysUserService.findSysUserById(sysUserLoginBean.getId());
        if (!BaseUtil.isEmpty(sysUser.getWyId())) {
            // 分配企业
            // Enterprise enterprise =
            // this.enterpriseService.findByEnterpriseId(sysUser.getWyId());
            // if(!BaseUtil.isEmpty(enterprise)){
            // //企业信息
            // this.sysUserBean.setWyId(enterprise.getWyId());
            // this.sysUserBean.setEnterpriseName(enterprise.getName());
            // }
            this.sysUserBean.setWyId(sysUser.getWyId());
            this.sysUserBean.setEnterpriseName(sysUser.getWyId() + "");
        }
        return SUCCESS;
    }

    // /**
    // * 添加人员
    // *
    // * @return
    // * @throws FrameworkException
    // */
    // @Action(value = "saveSysUser", results = {
    // @Result(name = "success", location = "/page/system/sys_user_list.jsp"),
    // @Result(name = "input", location = "/page/system/sys_user_detail.jsp") })
    // public String saveSysUser() throws FrameworkException, Exception {
    //
    // String simpleCode = "";
    // SearchBean comBean = new SearchBean();
    // comBean.addCondition(new ConditionBean(
    // SubcompanyEntity.COL_SUBCOMPANY_ID, ConditionType.EQUAL,
    // new Object[] { sysUserBean.getWyId() }));
    // List<SubcompanyEntity> subList =
    // communityCompanyService.getList(comBean);
    // if (subList.size() > 0) {
    // SubcompanyEntity sEntity = subList.get(0);
    // if (sEntity != null) {
    // simpleCode = sEntity.getSubcompanyCode();
    // }
    // }
    //
    // SysUserLoginBean sysUserLoginBean = (SysUserLoginBean) ActionContext
    // .getContext().getSession().get(CommonConstant.SESSION_USER);
    // if (simpleCode != "") {
    // if (!BaseUtil.isEmpty(this.sysUserService
    // .findSysUserByName(this.sysUserBean.getUserName()))) {
    // this.addFieldError("userName", "该用户已有相同账号!");
    // return INPUT;
    // }
    // }
    //
    // SysUser sysUser = new SysUser();
    // if (BaseUtil.isEmpty(this.sysUserBean.getPassword()))
    // this.sysUserBean.setPassword("123456");
    // BeanUtils.copyProperties(this.sysUserBean, sysUser);
    // //
    // sysUser.setPassword(DESUtil.getInstance().encrypt(sysUser.getPassword()));
    // sysUser.setPassword(MD5.getVsMd5(sysUser.getPassword()));
    //
    // sysUser.setFlag("1");
    // if (!BaseUtil.isEmpty(this.sysUserBean.getSysOrganizationIDs())) {
    // String[] orgIds = this.sysUserBean.getSysOrganizationIDs().split(
    // ",");
    // for (String orgId : orgIds) {
    // SysOrganization org = this.sysOrganizationService
    // .findSysOrganizationById(orgId);
    // org.getSysUsers().add(sysUser);
    // sysUser.getSysOrganizations().add(org);
    // }
    // }
    // if (!BaseUtil.isEmpty(this.sysUserBean.getSysRoleIDs())) {
    // String[] roleIds = this.sysUserBean.getSysRoleIDs().split(",");
    // for (String roleId : roleIds) {
    // SysRole role = this.sysRoleService.findSysRoleById(roleId);
    // role.getSysUsers().add(sysUser);
    // sysUser.getSysRoles().add(role);
    // }
    // }
    // SysUser createUser = this.sysUserService
    // .findSysUserById(sysUserLoginBean.getId());
    // sysUser.setWyId(createUser.getWyId());
    // sysUser.setOPtype(99);// 为消费系统修改权限，99为最低权限，1为最大权限
    // // if(BaseUtil.isEmpty(sysUser.getWyId())){
    // // sysUser.setWyId("1");
    // // }
    //
    // sysUser.setUserName(sysUserBean.getUserName());
    // this.sysUserService.saveSysUser(sysUser);
    //
    // return SUCCESS;
    // }

    // /**
    // * 修改人员
    // *
    // * @return
    // * @throws FrameworkException
    // */
    // @Action(value = "modifySysUser", results = {
    // @Result(name = "success", location = "/page/system/sys_user_list.jsp"),
    // @Result(name = "input", location = "/page/system/sys_user_modify.jsp") })
    // public String modifySysUser() throws FrameworkException, Exception {
    //
    // String simpleCode = "";
    // SearchBean comBean = new SearchBean();
    // comBean.addCondition(new ConditionBean(
    // SubcompanyEntity.COL_SUBCOMPANY_ID, ConditionType.EQUAL,
    // new Object[] { sysUserBean.getWyId() }));
    // List<SubcompanyEntity> subList =
    // communityCompanyService.getList(comBean);
    // if (subList.size() > 0) {
    // SubcompanyEntity sEntity = subList.get(0);
    // if (sEntity != null) {
    // simpleCode = sEntity.getSubcompanyCode();
    // }
    // }
    // if (simpleCode != "") {
    // if (!BaseUtil.isEmpty(this.sysUserService.findSysUserByIdAndName(
    // Integer.parseInt(this.sysUserBean.getId()),
    // this.sysUserBean.getUserName()))) {
    // this.addFieldError("name", "该用户已有相同账号!");
    // return INPUT;
    // }
    // }
    //
    // this.sysUserService.removeSysOrgAndSysRole(this.sysUserBean.getId()
    // + "");
    // SysUser sysUser = this.sysUserService.findSysUserById(Integer
    // .valueOf(this.sysUserBean.getId()));
    // if (BaseUtil.isEmpty(this.sysUserBean.getPassword())) {
    // // this.sysUserBean.setPassword("111111");
    // this.sysUserBean.setPassword(sysUser.getPassword());
    // BeanUtils.copyProperties(this.sysUserBean, sysUser);
    // //
    // sysUser.setPassword(DESUtil.getInstance().encrypt(sysUser.getPassword()));
    // // sysUser.setPassword(MD5.getVsMd5(sysUser.getPassword()));
    // this.sysUserService.modifySysUserByCondition(sysUser,
    // this.sysUserBean.getSysOrganizationIDs(),
    // this.sysUserBean.getSysRoleIDs());
    // } else {
    // BeanUtils.copyProperties(this.sysUserBean, sysUser);
    // sysUser.setPassword(MD5.getVsMd5(sysUser.getPassword()));
    // this.sysUserService.modifySysUserByCondition(sysUser,
    // this.sysUserBean.getSysOrganizationIDs(),
    // this.sysUserBean.getSysRoleIDs());
    // }
    // return SUCCESS;
    //
    // }

    /**
     * 通过人员ID获取获取人员及其关联角色信息
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "findSysRolesBySysUserId", results = {@Result(type = "json", params = {"excludeNullProperties",
            "true", "excludeProperties", "sysUserBean,sysUserBeans"})})
    @SkipValidation()
    public String findSysRolesBySysUserId() throws FrameworkException {
        SysUser sysUser = this.sysUserService.findSysUserById(Integer.parseInt(this.sysUserBean.getId()));
        BeanUtils.copyProperties(sysUser, this.sysUserBean);
        List<SysRole> sysRoles = sysUser.getSysRoles();
        for (SysRole sysRole : sysRoles) {
            SysRoleBean sysRoleBean = new SysRoleBean();
            BeanUtils.copyProperties(sysRole, sysRoleBean);
            this.sysRoleBeans.add(sysRoleBean);
        }
        return SUCCESS;
    }

    /**
     * 通过人员ID获取人员信息
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "findSysUser", results = {@Result(type = "json", name = "success", params = {"root", "jsonObject"})})
    @SkipValidation()
    public String findSysUser() throws FrameworkException, Exception {
        SysUser sysUser = this.sysUserService.findSysUserById(Integer.parseInt(this.sysUserBean.getId()));
        // BeanUtils.copyProperties(sysUser, this.sysUserBean);
        // bean里面的id数据类型和po里面id的数据类型不一致。所以这里用了apache的BeanUtils
        org.apache.commons.beanutils.BeanUtils.copyProperties(this.sysUserBean, sysUser);
        String orgIds = "";
        String orgNames = "";
        List<SysOrganization> orgs = sysUser.getSysOrganizations();
        if (!BaseUtil.isEmpty(orgs) && orgs.size() > 0) {
            for (SysOrganization org : orgs) {
                if (BaseUtil.isEmpty(orgIds)) {
                    orgIds = org.getId();
                    orgNames = org.getName();
                } else {
                    orgIds += "," + org.getId();
                    orgNames += "," + org.getName();
                }
            }
        }
        String roleIds = "";
        String roleNames = "";
        List<SysRole> roles = sysUser.getSysRoles();
        if (!BaseUtil.isEmpty(roles) && roles.size() > 0) {
            for (SysRole role : roles) {
                if (BaseUtil.isEmpty(roleIds)) {
                    roleIds = role.getId();
                    roleNames = role.getName();
                } else {
                    roleIds += "," + role.getId();
                    roleNames += "," + role.getName();
                }
            }
        }
        if (!BaseUtil.isEmpty(sysUser.getWyId())) {
            // 分配企业
            // Enterprise enterprise =
            // this.enterpriseService.findByEnterpriseId(sysUser.getWyId());
            // if(!BaseUtil.isEmpty(enterprise)){
            // //企业信息
            // this.sysUserBean.setWyId(enterprise.getWyId());
            // this.sysUserBean.setEnterpriseName(enterprise.getName());
            //
            //
            // }
            // CommunityCompany company = this.communityCompanyService.getCommunityCompanyById(sysUser.getWyId());
            this.sysUserBean.setWyId(sysUser.getWyId());
            // this.sysUserBean.setEnterpriseName(company.getCompanyName());
            // if (!BaseUtil.isEmpty(sysUser.getDeptId())
            // && sysUser.getDeptId() != 0) {
            // String deptName = departmentService.getDepartmentById(
            // sysUser.getDeptId()).getKeyName();
            // this.sysUserBean.setDeptName(deptName);
            // }
        }

        this.sysUserBean.setSysOrganizationIDs(orgIds);
        this.sysUserBean.setOrgNames(orgNames);
        this.sysUserBean.setSysRoleIDs(roleIds);
        this.sysUserBean.setRoleName(roleNames);
        this.sysUserBean.setPassword("null");// 密码设置为‘null’字符
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("sysUserBean", sysUserBean);
        jsonObject = JSONObject.fromObject(jsonMap);
        return SUCCESS;
    }

    /**
     * 通过人员ID删除人员信息
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "deleteSysUser", results = {@Result(name = "success", type = "chain", location = "findAllSysUsers")})
    @SkipValidation()
    public String deleteSysUser() throws FrameworkException {
        this.sysUserService.deleteSysUserById(Integer.parseInt(this.sysUserBean.getId()));
        return SUCCESS;
    }

    /**
     * 通过多个人员ID，系统删除多人员信息
     */
    @Action(value = "deleteSysUsers", results = {@Result(type = "json", name = "success", params = {"root",
            "jsonObject"})})
    @SkipValidation()
    public String deleteSysUsers() throws FrameworkException {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            this.sysUserService.deleteSysUsers(this.sysUserBean.getDeleteIDs().split(","));
            jsonMap.put("flag", true);
        } catch (Exception e) {
            jsonMap.put("flag", false);
            e.printStackTrace();
        }
        jsonObject = JSONObject.fromObject(jsonMap);
        return SUCCESS;
    }

    /**
     * 查询人员
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "findAllSysUsers", results = {@Result(type = "json", name = "success", params = {"root",
            "jsonObject"})})
    @SkipValidation()
    public String findAllSysUsers() throws FrameworkException, Exception {
        // jqGrid查询转码-utf-8
        BaseUtil.decodeObject(this.sysUserBean);
        SysUserLoginBean sysUserLoginBean =
                (SysUserLoginBean) ActionContext.getContext().getSession().get(CommonConstant.SESSION_USER);
        SysUser su = this.sysUserService.findSysUserById(sysUserLoginBean.getId());
        Map<String, Object> searchCondition = HqlUtil.beanToMap(this.sysUserBean, SysUser.class);
        searchCondition.remove("id");
        searchCondition.remove("deptId");
        // 如果是系统管理员，就能查询所有企业的用户
        if (BaseUtil.isEmpty(su.getWyId()) || su.getWyId() == 0) {
            searchCondition.remove("wyId");
        } else {
            searchCondition.put("wyId", su.getWyId());
        }
        // 手工构造操作员、状态查询条件
        searchCondition = buildDisabledAndOperatorCondition(searchCondition, this.sysUserBean);
        // this.pageBean.init(this.sysUserService
        // .getSysUserTotalRows(searchCondition));
        // 行数
        int pageSize = Integer.parseInt((String) ServletActionContext.getRequest().getParameter("rows"));
        // 当前页码数
        int pageIndex = Integer.parseInt((String) ServletActionContext.getRequest().getParameter("page"));
        List<SysUser> sysUsers = this.sysUserService.findAllSysUsers(searchCondition, pageIndex, pageSize);
        for (SysUser sysUser : sysUsers) {
            SysUserBean bean = new SysUserBean();
            // BeanUtils.copyProperties(sysUser, bean);
            // bean里面的id数据类型和po里面id的数据类型不一致。所以这里用了apache的BeanUtils
            org.apache.commons.beanutils.BeanUtils.copyProperties(bean, sysUser);
            List<SysOrganization> orgs = sysUser.getSysOrganizations();
            String tempOrgName = "";
            for (SysOrganization org : orgs) {
                if (BaseUtil.isEmpty(tempOrgName))
                    tempOrgName = org.getName();
                else
                    tempOrgName += ";" + org.getName();
            }
            bean.setOrgNames(tempOrgName);
            // bean.setPassword(DESUtil.getInstance().decrypt(bean.getPassword()));
            bean.setDisabledFlag(BaseUtil.booleanToChineseString(bean.getDisabled(), "启用", "禁用"));
            bean.setOperatorFlag(BaseUtil.booleanToChineseString(bean.getIsOperator()));
            bean.setGender(BaseUtil.isEmpty(bean.getGender()) ? "男" : SystemResourceUtil.getInstance()
                    .getCnNameOfBusinessDictionary("gender", bean.getGender()));
            this.sysUserBeans.add(bean);
        }
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("rows", sysUserBeans);
        jsonMap.put("total", this.sysUserService.getSysUserTotalRows(searchCondition));
        jsonObject = JSONObject.fromObject(jsonMap);
        return SUCCESS;
    }

    /**
     * 通过组织机构ID查询未与该组织机构关联的人员
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "findNotSelectedSysUsers", results = {@Result(type = "json")})
    @SkipValidation()
    public String findNotSelectedSysUsers() throws FrameworkException, Exception {
        // jqGrid查询转码-utf-8
        BaseUtil.decodeObject(this.sysUserBean);
        Map<String, Object> searchCondition = HqlUtil.beanToMap(this.sysUserBean, SysUser.class);
        this.pageBean.init(this.sysUserService.getNotSelectedSysUserTotalRows(this.sysUserBean.getSysOrganizationIDs(),
                searchCondition));
        List<SysUser> sysUsers =
                this.sysUserService.findNotSelectedSysUsers(this.sysUserBean.getSysOrganizationIDs(), searchCondition,
                        this.pageBean.getCurPage(), this.pageBean.getPageSize());
        for (SysUser sysUser : sysUsers) {
            SysUserBean bean = new SysUserBean();
            BeanUtils.copyProperties(sysUser, bean);
            bean.setGender(BaseUtil.isEmpty(bean.getGender()) ? "男" : SystemResourceUtil.getInstance()
                    .getCnNameOfBusinessDictionary("gender", bean.getGender()));
            this.sysUserBeans.add(bean);
        }
        return SUCCESS;
    }

    /**
     * 根据人员ID设置组织机构
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "setSysOrganization")
    @SkipValidation()
    public String setSysOrganization() throws FrameworkException {
        this.sysUserService.setSysOrganization(Integer.parseInt(this.sysUserBean.getId()), this.sysUserBean
                .getSysOrganizationIDs().split(","));
        return SUCCESS;
    }

    /**
     * 根据人员ID设置权限
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "setSysRole", results = {@Result(type = "json", params = {"excludeNullProperties", "true",
            "includeProperties", "result"})})
    @SkipValidation()
    public String setSysRole() throws FrameworkException {
        this.sysUserService
                .setSysRole(Integer.parseInt(this.sysUserBean.getId()), BaseUtil.isEmpty(this.sysUserBean
                        .getSysRoleIDs()) ? null : this.sysUserBean.getSysRoleIDs().split(","));
        result = true;
        return SUCCESS;
    }

    /**
     * 构造状态、操作员查询条件
     * 
     * @param params
     * @param sysUserBean
     * @return
     * @throws FrameworkException
     */
    private Map<String, Object> buildDisabledAndOperatorCondition(Map<String, Object> params, SysUserBean sysUserBean)
            throws FrameworkException {
        params = BaseUtil.isEmpty(params) ? new TreeMap<String, Object>() : params;
        params.put("disabled", true);
        if (!BaseUtil.isEmpty(sysUserBean)) {
            if (!BaseUtil.isEmpty(sysUserBean.getOperatorFlag())) {
                if (sysUserBean.getOperatorFlag().equals("true"))
                    params.put("isOperator", true);
                else if (sysUserBean.getOperatorFlag().equals("false")) params.put("isOperator", false);
            }
        }
        return params;

    }

    /**
     * 获取登录用户密码和用户名
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "findUserLoginInfo", results = {@Result(type = "json", params = {"excludeNullProperties", "true",
            "includeProperties", "oldPassword"})})
    @SkipValidation()
    public String findUserLoginInfo() {
        sysUserLoginBean = (SysUserLoginBean) ActionContext.getContext().getSession().get(CommonConstant.SESSION_USER);
        logger.debug("----userbean=" + sysUserLoginBean.getPassword());
        logger.debug("----userbean=" + sysUserLoginBean.getUserName());

        try {
            String npwd = MD5.getVsMd5(this.newpassword);
            if (npwd.equals(sysUserLoginBean.getPassword())) {
                oldPassword = "true";
            }
            // oldPassword = sysUserLoginBean.getPassword();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 一般用户修改密码
     * 
     * @return
     * @throws Exception
     */
    @Action(value = "userPasswordChange", results = {@Result(type = "json", params = {"excludeNullProperties", "true",
            "includeProperties", "result"})})
    @SkipValidation()
    public String userPasswordChange() throws Exception {
        sysUserLoginBean = (SysUserLoginBean) ActionContext.getContext().getSession().get(CommonConstant.SESSION_USER);
        SysUser sysUser = this.sysUserService.findSysUserById(sysUserLoginBean.getId());
        // String password =
        // DESUtil.getInstance().decrypt(sysUser.getPassword());
        String password = sysUser.getPassword();
        logger.debug("password=" + password);
        logger.debug("newpassword=" + sysUserBean.getPassword());
        String pwd = MD5.getVsMd5(sysUserBean.getPassword());
        // if (sysUserBean.getPassword().equalsIgnoreCase(password)) {
        if (pwd.equalsIgnoreCase(password)) {
            // sysUser.setPassword(DESUtil.getInstance().encrypt(this.newpassword));
            sysUser.setPassword(MD5.getVsMd5(this.newpassword));
            this.sysUserService.modifySysUser(sysUser);
            // sysUserLoginBean.setPassword(this.newpassword);
            sysUserLoginBean.setPassword(sysUser.getPassword());
            ActionContext.getContext().getSession().put(CommonConstant.SESSION_USER, sysUserLoginBean);
            result = true;
        } else {
            result = false;
        }
        logger.debug("result=" + result);
        return SUCCESS;
    }

    /**
     * 恢复初始密码
     * 
     * @return
     * @throws Exception
     */
    @Action(value = "initPassword", results = {@Result(type = "json", name = "success", params = {"root", "jsonObject"})})
    @SkipValidation()
    public String initPassword() throws Exception {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            this.sysUserService.initPassword(this.sysUserBean.getDeleteIDs().split(","));
            jsonMap.put("flag", true);
        } catch (Exception e) {
            jsonMap.put("flag", false);
            e.printStackTrace();
        }
        jsonObject = JSONObject.fromObject(jsonMap);
        return SUCCESS;
    }

    /**
     * 添加人员
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "saveSysTemUser", results = {@Result(type = "json", name = "success", params = {"root",
            "jsonObject"})})
    public String saveSysTemUser() throws FrameworkException, Exception {
        BaseUtil.decodeObject(sysUserBean);
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        SysUser sysUser = null;
        // 判断是新增还是修改
        if (!BaseUtil.isEmpty(sysUserBean.getId())) {
            sysUser = this.sysUserService.findSysUserById(Integer.parseInt(sysUserBean.getId()));
            if (!BaseUtil.isEmpty(sysUserBean.getPassword()) && sysUserBean.getPassword().equals("null")) {
                sysUser.setPassword(MD5.getVsMd5(sysUserBean.getPassword()));
            }
            sysUser.setRealName(sysUserBean.getRealName());
            sysUser.setIdentityCard(sysUserBean.getIdentityCard());
            sysUser.setMobile(sysUserBean.getMobile());
            sysUser.setUpdatetime(new Date());
            // 先全部删除组织和权限在挂接
            this.sysUserService.removeSysOrgAndSysRole(this.sysUserBean.getId() + "");
        } else {
            sysUser = new SysUser();
            // BeanUtils.copyProperties(this.sysUserBean, sysUser);
            // bean里面的id数据类型和po里面id的数据类型不一致。所以这里用了apache的BeanUtils
            org.apache.commons.beanutils.BeanUtils.copyProperties(sysUser, this.sysUserBean);
            String simpleCode = "";// 公司简码
            // SearchBean comBean = new SearchBean();
            int wyId = sysUserBean.getWyId();
            // comBean.addCondition(new ConditionBean(
            // CommunityCompany.COL_COMPANY_ID, ConditionType.EQUAL,
            // new Object[] { wyId }));
            // List<CommunityCompany> companyList = communityCompanyService
            // .getList(comBean);
            // if (companyList != null && companyList.size() > 0) {
            // CommunityCompany sEntity = companyList.get(0);
            // if (sEntity != null) {
            // simpleCode = sEntity.getCompanyCode();
            // }
            // }
            // 判断同企业下是否有重复
            if (simpleCode != "") {
                if (!BaseUtil.isEmpty(this.sysUserService.findSysUserByName(this.sysUserBean.getUserName() + "@"
                        + simpleCode))) {
                    jsonMap.put("flag", false);
                    jsonMap.put("content", "该用户已有相同账号!");
                    jsonObject = JSONObject.fromObject(jsonMap);
                    return SUCCESS;
                }
            }
            // sysUser.setFlag("1");
            sysUser.setDisabled(true);
            sysUser.setWyId(wyId);
            // 用户名加企业简码
            sysUser.setUserName(sysUserBean.getUserName() + "@" + simpleCode);
            sysUser.setIsOperator(true);
            sysUser.setGender("1");
            sysUser.setCreatetime(new Date());
            // sysUser.setOPtype(1);
            if (BaseUtil.isEmpty(this.sysUserBean.getPassword())) this.sysUserBean.setPassword("111111");
            // sysUser.setPassword(DESUtil.getInstance().encrypt(sysUser.getPassword()));
            sysUser.setPassword(MD5.getVsMd5(sysUser.getPassword()));
        }
        // 组织机构
        if (!BaseUtil.isEmpty(this.sysUserBean.getSysOrganizationIDs())) {
            String[] orgIds = this.sysUserBean.getSysOrganizationIDs().split(",");
            for (String orgId : orgIds) {
                SysOrganization org = this.sysOrganizationService.findSysOrganizationById(orgId);
                org.getSysUsers().add(sysUser);
                sysUser.getSysOrganizations().add(org);
            }
        }
        // 权限
        if (!BaseUtil.isEmpty(this.sysUserBean.getSysRoleIDs())) {
            String[] roleIds = this.sysUserBean.getSysRoleIDs().split(",");
            for (String roleId : roleIds) {
                SysRole role = this.sysRoleService.findSysRoleById(roleId);
                role.getSysUsers().add(sysUser);
                sysUser.getSysRoles().add(role);
            }
        }
        // 判断是新增还是修改
        if (!BaseUtil.isEmpty(sysUserBean.getId())) {
            this.sysUserService.modifySysUser(sysUser);
        } else {
            this.sysUserService.saveSysUser(sysUser);
        }
        jsonMap.put("flag", true);
        jsonObject = JSONObject.fromObject(jsonMap);
        return SUCCESS;
    }

    /**
     * 根据id查询人员
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "findSysTemUser", results = {@Result(type = "json", name = "success", params = {"root",
            "jsonObject"})})
    @SkipValidation()
    public String findSysTemUser() throws FrameworkException, Exception {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        SysUser sysUser = null;
        // 用户id
        String sysUserId = this.sysUserBean.getId();
        if (!BaseUtil.isEmpty(sysUserId)) {
            // 查询user实体
            sysUser = this.sysUserService.findSysUserById(Integer.parseInt(sysUserId));
            // 通过实体获取当前实体权限
            List<SysRole> roleList = sysUser.getSysRoles();
            List<String> roleIds = new ArrayList<String>();
            for (SysRole sysRole : roleList) {
                roleIds.add(sysRole.getId());
            }
            jsonMap.put("flag", true);
            jsonMap.put("roleIds", roleIds);
        } else {
            jsonMap.put("flag", false);
        }
        jsonObject = JSONObject.fromObject(jsonMap);
        return SUCCESS;
    }

    /**
     * 根据人员ID设置权限
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "saveUserSysRole", results = {@Result(type = "json", name = "success", params = {"root",
            "jsonObject"})})
    @SkipValidation()
    public String saveUserSysRole() throws FrameworkException {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            this.sysUserService.setSysRole(
                    Integer.parseInt(this.sysUserBean.getId()),
                    BaseUtil.isEmpty(this.sysUserBean.getSysRoleIDs()) ? null : this.sysUserBean.getSysRoleIDs().split(
                            ","));
            jsonMap.put("flag", true);
        } catch (Exception e) {
            jsonMap.put("flag", false);
            logger.warn(e.getMessage());
        }
        jsonObject = JSONObject.fromObject(jsonMap);
        return SUCCESS;
    }

    /**
     * 去后台获取当前登录人所属物业公司
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "initCompanyName", results = {@Result(type = "json", name = "success", params = {"root",
            "jsonObject"})})
    @SkipValidation()
    public String initCompanyName() throws FrameworkException {
        SysUserLoginBean sysUserLoginBean =
                (SysUserLoginBean) ActionContext.getContext().getSession().get(CommonConstant.SESSION_USER);
        SysUser sysUser = this.sysUserService.findSysUserById(sysUserLoginBean.getId());
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        // 所属公司不属于空
        if (!BaseUtil.isEmpty(sysUser.getWyId()) && sysUser.getWyId() != 0) {
            jsonMap.put("flag", true);
            jsonMap.put("wyId", sysUser.getWyId());
            jsonMap.put("companyName", "宗申物业管理公司");
        }
        jsonObject = JSONObject.fromObject(jsonMap);
        return SUCCESS;
    }

}
